import {useState} from 'react';
import { styled, useTheme } from '@mui/material/styles';
import Box from '@mui/material/Box';
import MuiDrawer from '@mui/material/Drawer';
import MuiAppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import List from '@mui/material/List';
import CssBaseline from '@mui/material/CssBaseline';
import Typography from '@mui/material/Typography';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import PeopleAltIcon from '@mui/icons-material/PeopleAlt';
import { NavLink } from 'react-router-dom';
import DashboardIcon from '@mui/icons-material/Dashboard';
import HomeIcon from '@mui/icons-material/Home';
import AccountCircle from '@mui/icons-material/AccountCircle';
import MenuItem from '@mui/material/MenuItem';
import Menu from '@mui/material/Menu';
import { Outlet } from "react-router-dom";
import { useAuth } from './hooks';

const drawerWidth = 240;
const openedMixin = (theme) => ({
  width: drawerWidth,
  transition: theme.transitions.create('width', {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.enteringScreen,
  }),
  overflowX: 'hidden',
});

const closedMixin = (theme) => ({
  transition: theme.transitions.create('width', {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  overflowX: 'hidden',
  width: `calc(${theme.spacing(7)} + 1px)`,
  [theme.breakpoints.up('sm')]: {
    width: `calc(${theme.spacing(8)} + 1px)`,
  },
});

const DrawerHeader = styled('div')(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'flex-end',
  padding: theme.spacing(0, 1),
  ...theme.mixins.toolbar,
}));

const AppBar = styled(MuiAppBar, {
  shouldForwardProp: (prop) => prop !== 'open',
})(({ theme }) => ({
  zIndex: theme.zIndex.drawer + 1,
  transition: theme.transitions.create(['width', 'margin'], {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  variants: [
    {
      props: ({ open }) => open,
      style: {
        marginLeft: drawerWidth,
        width: `calc(100% - ${drawerWidth}px)`,
        transition: theme.transitions.create(['width', 'margin'], {
          easing: theme.transitions.easing.sharp,
          duration: theme.transitions.duration.enteringScreen,
        }),
      },
    },
  ],
}));

const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })(
  ({ theme }) => ({
    width: drawerWidth,
    flexShrink: 0,
    whiteSpace: 'nowrap',
    boxSizing: 'border-box',
    variants: [
      { props: ({ open }) => open, style: { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }, },
      { props: ({ open }) => !open, style: { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }, },
    ],
  }),
);

const menus = [
  { name: 'Users', path: '/users', role:"Admin"},
  { name: 'Rooms', path: '/rooms' , role:"Admin"},
  { name: 'Booking', path: '/bookings' , role:null}
];

export default function MiniDrawer() {
  const theme = useTheme();
  const {user,logout}=useAuth();
  const [open, setOpen] = useState(false);  
  const [anchorEl, setAnchorEl] = useState(null);

  const handleMenu = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const onClose = () => {
    setAnchorEl(null);
  };
  
  const onLogout=()=>{
    logout();
    window.location.href = "/login";
  }
  return (
    <Box sx={{ display: 'flex' }}>
      <CssBaseline />
      <AppBar position="fixed" open={open}>
        <Toolbar>
          <IconButton
            color="inherit"
            aria-label="open drawer"
            onClick={() => setOpen(true)}
            edge="start"
            sx={[{ marginRight: 5, }, open && { display: 'none' },]}>
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" noWrap component="div">
            Meeting Room Booking System
          </Typography>
          {(
            <div style={{ position: 'absolute', right: 30 }}>
              <IconButton
                size="large"
                aria-label="account of current user"
                aria-controls="menu-appbar"
                aria-haspopup="true"
                onClick={handleMenu}
                color="inherit"
              >
                <AccountCircle />
              </IconButton><Typography variant="h7" noWrap component="span">{user?.userName}</Typography>
              <Menu
                id="menu-appbar"
                anchorEl={anchorEl}
                anchorOrigin={{
                  vertical: 'top',
                  horizontal: 'right',
                }}
                keepMounted
                transformOrigin={{
                  vertical: 'top',
                  horizontal: 'right',
                }}
                open={Boolean(anchorEl)}
                onClose={onClose}
              >
                <MenuItem onClick={onLogout}>Logout</MenuItem>
                
              </Menu>
            </div>
          )}
        </Toolbar>
      </AppBar>
      <Drawer variant="permanent" open={open}>
        <DrawerHeader>
          <Typography align='left' variant="h6" noWrap component="div">Meeting</Typography> <IconButton onClick={() => setOpen(false)}>
            {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />}
          </IconButton>
        </DrawerHeader>
        <Divider />
        <List>
          {menus.map((item, index) => (          
            <NavLink key={item.name} to={item.path} style={{ display: (item.role==null || (item.role&& item.role === user?.role)) ? 'block' : 'none' }}>
              <ListItem key={item.name} disablePadding sx={{ display: 'block' }} >
                <ListItemButton
                  sx={[{ minHeight: 48, px: 2.5, },
                  open ? { justifyContent: 'initial', } : { justifyContent: 'center', },]}>
                  <ListItemIcon sx={[{ minWidth: 0, justifyContent: 'center', }, open ? { mr: 3, } : { mr: 'auto', },]}>
                    {item.name === 'Users' ? <PeopleAltIcon /> : item.name === 'Booking' ? <DashboardIcon /> : <HomeIcon />}
                  </ListItemIcon>
                  <ListItemText primary={item.name} sx={[open ? { opacity: 1, } : { opacity: 0, }]} />
                </ListItemButton>
              </ListItem>
            </NavLink>
          ))}
        </List>
      </Drawer>
      <Box component="main" sx={{ flexGrow: 1, p: 3 }}>
        <DrawerHeader />
        {/* <Routes>          
          <Route path="/users" element={<Users />} />
          <Route path="/user-create" element={<CreateUser />} />
          <Route path="/user-edit/:useId/:userName/:email/:role" element={<EditUser />} />
          <Route path="/bookings" element={<Bookings />} />
          <Route path="/booking-create" element={<CreateBooking />} />
          <Route path="/rooms" element={<Rooms />} />
          <Route path="/room-create" element={<CreateRoom />} />
          <Route path="/room-edit" element={<EditRoom />} />
          <Route path="/" element={<Navigate to='/users' />} />
        </Routes> */}
        <Outlet />
      </Box>
    </Box>
  );
}